package com.test.study;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.test.study.pojo.GpRpcReq;
import com.test.study.util.SerializationUtil;

public class TCPTransport {

	private String host;
	private int port;
	
	public TCPTransport(String host, Integer port) {
        this.host = host;
        this.port = port;
    }
    private Socket newSocket(){
        try {
            return new Socket(host,port);
        } catch (IOException e) {
            throw new RuntimeException("连接建立失败");
        }
    }
    
    public Object send(GpRpcReq req){
    	Socket socket = newSocket();
    	// 发送远程请求
		Object result = null;
		DataOutputStream out = null;
		DataInputStream input = null;
		byte[] reqStr = null;
		try {
			out = new DataOutputStream(socket.getOutputStream());
			reqStr = SerializationUtil.serialize(req);
			int len = 4+ reqStr.length;
			out.writeInt(len);
			out.write(reqStr);
			out.flush();
			socket.shutdownOutput();
			
			input = new DataInputStream(socket.getInputStream());
			result = parseReq(input);
			
			input.close();
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			return result;
		}
		
    }
    
    public String parseReq(DataInputStream input) throws IOException{
    	int len = input.readInt();
    	byte[] data = new byte[len-4];
    	input.readFully(data);
		return new String(data,"UTF-8");
	}
    
    
}
